import Vue from 'vue'
import groupBy from 'lodash.groupby'
import defu from 'defu'

const userInit = {
  id: '',
  hasLogined: false,
  username: '',
  nicookiesname: '',
  avatar: '',
  homepage: '',
  connect: {},
  media: {},
  status: {},
  detail: {},
  education: [],
  career: [],
  friends: [],
  following: [],
  follow_by: [],
  favoring: [],
  blacookiesing: [],
  scopes: [],
  times: [],
}

export const state = () => ({
  cookieExpire: 7 * 24 * 60 * 60,
  user: { ...userInit },
  token: '',

  // 南川文件/路由导航系统
  pathTree: {},
  // title: '南川笔记',
  settings: {},
})

export const getters = {
  settings(state) {
    return state.settings
  },
  user(state) {
    return state.user
  },
}

export const mutations = {
  SET_DATA(state, payload) {
    let key
    let val
    if (Object.keys(payload).length === 2) {
      key = payload.key
      val = payload.var
    } else if (Object.keys(payload).length === 1) {
      key = Object.keys(payload)[0]
      val = payload[key]
    } else {
      throw new Error('store payload not qualified')
    }
    try {
      eval(`state.${key}=${val}`)
    } catch (err) {
      console.warn({ err })
      throw new Error(err)
    }
  },

  SET_USER(state, payload) {
    // console.log('updating user: ', payload)
    state.user = Object.assign({}, state.user, payload)
    if (process.client) {
      this.$cookies.set('user', state.user, {
        maxAge: state.cookieExpire,
        path: '/',
      })
    }
  },

  SET_TOKEN(state, tokenValue) {
    // console.log('updating token: ', tokenValue)
    state.token = tokenValue
    if (process.client) {
      this.$cookies.set('token', tokenValue, {
        maxAge: state.cookieExpire,
        path: '/',
      })
    }
    // sessionStorage.setItem('token', tokenValue)
    // console.log('updated session token')
  },

  RESET_USER(state) {
    state.user = { ...userInit }
    this.$cookies.removeAll()
    // console.log('[CLIENT] removing cookies of user and token...')
    // this.$cookies.remove('user')
    // console.log('now the user', this.$cookies.get('user'))
    // this.$cookies.remove('token')
    // console.log('now the token', this.$cookies.get('token'))
  },

  SET_SETTINGS(state, settings) {
    state.settings = Object.assign({}, settings)
  },

  SET_PATH_TREE(state, payload) {
    // console.log({ payload })
    state.pathTree = Object.assign({}, payload)
  },
}

export const actions = {
  nuxtServerInit({ commit, req }, { app }) {
    // set cookie
    // console.log({ app })
    const cookies = app.$cookies
    // console.log({ cookies })
    if (cookies.get('token')) {
      commit('SET_TOKEN', cookies.get('token'))
    }
    if (cookies.get('user')) {
      commit('SET_USER', cookies.get('user'))
    }
  },

  // nuxtClientInit({ commit }, { req }) {
  //   const userData = localStorage.getItem('user')
  //   if (userData) {
  //     commit('SET_USER', JSON.parse(userData))
  //     // commit('SET_DATA', { user: JSON.parse(userData) })
  //     console.log('INIT USER from nuxtClientInit')
  //   } else {
  //     commit('SET_USER', userInit)
  //     console.log('INIT USER based on userInit')
  //   }
  // },

  /**
   * 这个函数用于读取内容目录的settings文件，从而生成一些meta信息
   * @param commit
   * @returns {Promise<void>}
   */
  async fetchSettings({ commit }) {
    try {
      const settings = await this.$content('settings').fetch()
      commit('SET_SETTINGS', settings)
    } catch (e) {
      // eslint-disable-next-line no-console
      console.warn(
        'You can add a `settings.json` file inside the `content/` folder to customize this theme.'
      )
    }
  },

  fetchPathTree({ commit }) {
    const pathTree = {}
    const langs = ['en', 'zh']
    langs.forEach((lang) => {
      pathTree[lang] = require(`./pathMap/${lang}.json`)
    })
    commit('SET_PATH_TREE', pathTree)
  },
}
